package JDK常用类库.lambda;

import org.junit.Test;
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author zx
 * @create 2023-08-02 22:33
 * 一：构造器引用
 *      和方法引用类似，函数式接口的抽象方法的形参列表和构造器的形参列表一致。
 *      抽象方法的返回值类型即为构造器所属的类的类型
 * 二：数组引用
 *      把数组看为一个特殊的类，则写法与构造器引用一致。
 */
public class ConstructorTest {
    /**
     * 空参构造器引用
     */
    @Test
    public void test1(){
        Supplier<Person> sup1 = new Supplier<Person>() {
                        @Override
            public Person get() {
                return new Person();
            }
        };
        System.out.println(sup1.get());

        Supplier<Person> sup2 = () -> {
            return new Person();
        };
        System.out.println(sup2.get());

        Supplier<Person> sup3 = Person::new;
        System.out.println(sup3.get());
    }

    /**
     * Function中的R apply(T t)
     */
    @Test
    public void test2(){
        Function<Integer,Person> func1 = age -> new Person(age);
        Person person1 = func1.apply(23);
        System.out.println(person1);

        Function<Integer,Person> func2 = Person::new;
        Person person2 = func2.apply(24);
        System.out.println(person2);
    }

    /**
     * BiFunction中的R apply(T t, U u)
     */
    @Test
    public void test3(){
        BiFunction<String,Integer,Person> function1 = (name,age) -> new Person(name,age);
        Person p1 = function1.apply("韩韩", 21);
        System.out.println(p1);

        BiFunction<String,Integer,Person> function2 = Person::new;
        Person p2 = function2.apply("张三", 22);
        System.out.println(p2);
    }

    /**
     * 数组引用
     */
    @Test
    public void test4(){
        Function<Integer,String[]> func1 = length -> new String[length];
        String[] arr1 = func1.apply(5);
        System.out.println(Arrays.toString(arr1))
        ;
        Function<Integer,String[]> func2 = String[]::new;
        String[] arr2 = func2.apply(5);
        System.out.println(Arrays.toString(arr2));
    }
}
class Person{
    private String name;
    private int age;

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    private int height;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Person(String name, int age, int height) {
        this.name = name;
        this.age = age;
        this.height = height;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Person(int age) {
        this.age = age;
    }
    public Person() {

    }
}
